<template>
  <el-dialog :close-on-click-modal="false" :visible.sync="visible" width="80%">
    <el-row>
      <!--step-->
      <el-col :span="24">
        <el-steps :active="step" finish-status="success">
          <el-step title="基本信息"></el-step>
          <el-step title="规格参数"></el-step>
          <el-step title="销售属性"></el-step>
          <el-step title="SKU信息"></el-step>
          <el-step title="保存完成"></el-step>
        </el-steps>
      </el-col>
      <el-col :span="24" v-show="step == 0">
        <el-card class="box-card" style="width:80%;margin:20px auto">
          <el-form ref="spuBaseForm" :model="spu" label-width="120px" :rules="Rules">
            <el-form-item label="选择分类" prop="cid">
              <el-cascader
                v-model="paths"
                :options="categorys"
                @change="casecaderChange"
                ref="categoryCase"
                :props="casecaderSetting"
                filterable
              ></el-cascader>
            </el-form-item>
            <el-form-item label="选择品牌" prop="brandId">
              <el-select v-model="spu.brandId" placeholder="请选择" @change="brandChange">
                <el-option v-for="brand in brands" :key="brand.brandId" :label="brand.brandName" :value="brand.brandId">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="商品标题" prop="title">
              <el-input v-model="spu.title"></el-input>
            </el-form-item>
            <el-form-item label="商品卖点" prop="subTitle">
              <el-input v-model="spu.subTitle"></el-input>
            </el-form-item>
            <el-form-item label="包装清单" prop="spuDetail.packingList">
              <el-input v-model="spu.spuDetail.packingList"></el-input>
            </el-form-item>
            <el-form-item label="售后服务" prop="spuDetail.afterService">
              <el-input v-model="spu.spuDetail.afterService"></el-input>
            </el-form-item>

            <el-form-item label="商品图集" prop="description">
              <multi-upload v-model="images"></multi-upload>
            </el-form-item>
            <el-form-item>
              <el-button type="success" @click="collectSpuBaseInfo">下一步：设置基本参数</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
      <el-col :span="24" v-show="step == 1">
        <el-card class="box-card" style="width:50%;margin:20px auto">
          <el-tabs tab-position="left" style="width:98%">
            <el-tab-pane v-for="(group, groupId) in specparam" :label="group.groupName" :key="group.groupId">
              <!-- 遍历属性,每个tab-pane对应一个表单，每个属性是一个表单项  spu.baseAttrs[0] = [{attrId:xx,val:}]-->
              <el-form ref="form" :model="spu">
                <el-form-item v-for="(specparam, id) in group.data" :label="specparam.name" :key="specparam.id">
                  <el-input v-model="specKV[groupId][id].id" type="hidden" v-show="false"> </el-input>
                  <el-input
                    v-model="specKV[groupId][id].paramValue"
                    type="text"
                    v-show="true"
                    size="mini"
                    style="width: 300px;"
                  >
                  </el-input>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
          <div style="margin:auto">
            <el-button type="primary" @click="step = 0">上一步</el-button>
            <el-button type="success" @click="generateSaleAttrs">下一步：设置销售属性</el-button>
          </div>
        </el-card>
      </el-col>
      <el-col :span="24" v-show="step == 2">
        <el-card class="box-card" style="width:80%;margin:20px auto">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>选择销售属性</span>
              <el-form ref="saleform" :model="spu">
                <el-form-item v-for="(saleAttr, id) in saleAttrs" :label="saleAttr.paramName" :key="saleAttr.id">
                  <el-input v-model="saleAttr.id" type="hidden" v-show="false"> </el-input>
                  <el-input v-model="saleAttr.paramValue" type="text" v-show="true"> </el-input>
                </el-form-item>
              </el-form>
            </div>
            <el-button type="primary" @click="step = 1">上一步</el-button>
            <el-button type="success" @click="generateSkus">下一步：设置SKU信息</el-button>
          </el-card>
        </el-card>
      </el-col>
      <el-col :span="24" v-show="step == 3">
        <el-card class="box-card" style="width:80%;margin:20px auto">
          <el-table :data="tempSku" style="width: 100%">
            <el-table-column label="属性组合">
              <el-table-column :label="item.paramName" v-for="(item, index) in saleAttrs" :key="item.id">
                <template slot-scope="scope">
                  <span style="margin-left: 10px">{{ scope.row.ownSpec[index] }}</span>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column label="标题" prop="title">
              <template slot-scope="scope">
                <el-input v-model="scope.row.title"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="价格" prop="price">
              <template slot-scope="scope">
                <el-input v-model="scope.row.price"></el-input>
              </template>
            </el-table-column>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-row>
                  <el-col :span="24">
                    <single-upload v-model="scope.row.image"></single-upload>
                  </el-col>
                </el-row>
              </template>
            </el-table-column>
          </el-table>
          <el-button type="primary" @click="step = 2">上一步</el-button>
          <el-button type="success" @click="submitSkus">下一步：保存商品信息</el-button>
        </el-card>
      </el-col>
      <el-col :span="24" v-show="step == 4">
        <el-card class="box-card" style="width:80%;margin:20px auto">
          <h1>保存成功</h1>
          <el-button type="primary" @click="addAgian">继续添加</el-button>
        </el-card>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import CategoryCascader from '../common/category-cascader'
import BrandSelect from '../common/brand-select'
import MultiUpload from '@/components/upload/multiUpload'
import SingleUpload from '../../../components/upload/singleUpload'
import spudetail from './spudetail'

export default {
  //import引入的组件需要注入到对象中才能使用
  components: { SingleUpload, CategoryCascader, BrandSelect, MultiUpload },
  props: {},
  data() {
    return {
      visible: false,
      images: [],
      tempSku: [],
      specKV: [],
      specparam: [],
      saleAttrs: [],
      spu: {
        id: '',
        title: '',
        subTitle: '',
        cid1: 0,
        cid2: 0,
        cid3: 0,
        brandId: '',
        saleable: 0,
        valid: 0,
        createTime: '',
        lastUpdateTime: '',
        cname: '',
        bname: '',
        spuDetail: {
          spuId: '',
          description: '',
          genericSpec: '',
          specialSpec: {},
          packingList: '',
          afterService: ''
        },
        skus: []
      },
      paths: [],
      casecaderSetting: {
        value: 'id',
        label: 'name',
        children: 'children'
      },
      categorys: [],
      brands: [],
      step: 0,
      Rules: {
        title: [{ required: true, message: '请输入商品名字', trigger: 'blur' }],
        subTitle: [{ required: true, message: '请编写一个商品卖点', trigger: 'blur' }],
        packingList: [{ required: true, message: '请输入包装清单', trigger: 'blur' }],
        afterService: [{ required: true, message: '请输入售后服务', trigger: 'blur' }]
      }
    }
  },
  //计算属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  //方法集合
  methods: {
    init(id) {
      this.spu.id = id || 0
      this.visible = true
    },
    submitSkus() {
      this.tempSku.forEach((sku, index) => {
        this.spu.skus.push({
          id: sku.id,
          spuId: sku.spuId,
          title: sku.title,
          images: sku.images,
          price: sku.price,
          indexes: sku.indexes,
          ownSpec: {},
          enable: 1,
          createTime: '',
          lastTime: ''
        })
        let obj = {}
        sku.ownSpec.forEach((spec, i) => {
          obj[this.saleAttrs[i].id] = spec
        })
        this.spu.skus[index].ownSpec = JSON.stringify(obj)
      })
      this.$http({
        url: this.$http.adornUrl('/item/goods/save'),
        method: 'post',
        data: this.$http.adornData(this.spu, false)
      }).then(({ data }) => {
        if (data.code == 0) {
          this.$message({
            type: 'success',
            message: '新增商品成功!'
          })
          this.step = 4
        } else {
          this.$message({
            type: 'error',
            message: '保存失败，原因【' + data.msg + '】'
          })
        }
      })
      console.log(this.spu)
    },
    brandChange(item) {
      this.$http({
        url: this.$http.adornUrl(`/item/brand/info/${item}`),
        method: 'get'
      }).then(({ data }) => {
        this.spu.bname = data.brand.name
      })
    },
    //TODO 设置SKU
    generateSkus() {
      let temp = []
      this.spu.skus = []
      this.skus = []
      let spuDetailSpecialSpecTemp = {}
      this.saleAttrs.forEach(saleAttr => {
        spuDetailSpecialSpecTemp[saleAttr.id] = saleAttr.paramValue.split(',')
        temp.push(saleAttr.paramValue.split(','))
      })
      this.spu.spuDetail.specialSpec = JSON.stringify(spuDetailSpecialSpecTemp)
      //生成笛卡尔积
      // last为上次运算的结果，current为数组中的当前元素
      let decar = temp.reduce((last, current) => {
        const array = []
        last.forEach(par1 => {
          current.forEach(par2 => {
            array.push(par1 + ',' + par2)
          })
        })
        return array
      })
      decar.forEach((item, i) => {
        this.tempSku.push({
          id: '',
          spuId: '',
          title: '',
          images: '',
          price: '',
          indexes: '',
          ownSpec: item.split(','),
          enable: '',
          createTime: '',
          lastTime: ''
        })
      })
      this.step = 3
    },
    generateSaleAttrs() {
      const spec = {}
      this.specKV.forEach(item => {
        item.forEach(KV => {
          spec[KV.id] = KV.paramValue
        })
      })
      this.spu.spuDetail.genericSpec = JSON.stringify(spec)
      this.step = 2
      this.getShowSaleAttr()
    },
    getCategorys() {
      this.$http({
        url: this.$http.adornUrl('/item/category/list/tree'),
        method: 'get'
      }).then(({ data }) => {
        this.categorys = data.data
      })
    },
    getBrand(cid) {
      this.$http({
        url: this.$http.adornUrl(`/item/categorybrand/catelog/brands/${cid}`),
        method: 'get'
      }).then(({ data }) => {
        data.data.forEach(brand => {
          if (brand.brandName != '') {
            this.brands.push(brand)
          }
        })
      })
    },
    casecaderChange(node) {
      this.$http({
        url: this.$http.adornUrl(`/item/category/info/${node[node.length - 1]}`),
        method: 'get'
      }).then(({ data }) => {
        this.spu.cname = data.category.name
      })
      this.getBrand(node[node.length - 1])
    },
    addAgian() {
      this.step = 0
      this.resetSpuData()
    },
    resetSpuData() {
      ;(this.images = []),
        (this.tempSku = []),
        (this.specKV = []),
        (this.specparam = []),
        (this.saleAttrs = []),
        (this.spu = {
          id: '',
          title: '',
          subTitle: '',
          cid1: 0,
          cid2: 0,
          cid3: 0,
          brandId: '',
          saleable: 0,
          valid: 0,
          createTime: '',
          lastUpdateTime: '',
          cname: '',
          bname: '',
          spuDetail: {
            spuId: '',
            description: '',
            genericSpec: '',
            specialSpec: {},
            packingList: '',
            afterService: ''
          },
          skus: []
        }),
        (this.paths = []),
        (this.categorys = []),
        (this.brands = []),
        (this.step = 0),
        this.getCategorys()
    },
    collectSpuBaseInfo() {
      this.spu.spuDetail.description = this.images.join(',')
      console.log(this.spu.spuDetail.description)
      this.spu.cid1 = this.paths[0]
      this.spu.cid2 = this.paths[1]
      this.spu.cid3 = this.paths[2]
      //spuBaseForm
      this.$refs.spuBaseForm.validate(valid => {
        if (valid) {
          this.step = 1
          this.showBaseAttrs()
        } else {
          return false
        }
      })
    },
    getShowSaleAttr() {
      //获取当前分类可以使用的销售属性
      this.$http({
        url: this.$http.adornUrl(`/item/specparam/list/sale/${this.spu.cid3}`),
        method: 'get'
      }).then(({ data }) => {
        let saleAttrTemp = []
        data.data.forEach(item => {
          saleAttrTemp.push({
            id: item.id,
            paramName: item.name,
            paramValue: ''
          })
        })
        this.saleAttrs = saleAttrTemp
        console.log(this.saleAttrs)
      })
    },
    showBaseAttrs() {
      this.specparam = []
      this.specKV = []
      this.$http({
        url: this.$http.adornUrl(`/item/specparam/list/base/${this.spu.cid3}`),
        method: 'get',
        params: this.$http.adornParams({})
      }).then(({ data }) => {
        let temp = []
        let groupObj = {}
        let groupArr = []
        data.data.forEach(item => {
          if (temp.indexOf(item.groupId) == -1) {
            temp.push(item.groupId)
            groupObj = { groupId: item.groupId, groupName: item.groupName }
            groupArr.push(groupObj)
          }
        })
        groupArr.forEach(group => {
          let arr = []
          let KVarr = []
          data.data.forEach(spec => {
            if (group.groupId == spec.groupId) {
              let temp = { id: spec.id, name: spec.name }
              arr.push(temp)
              KVarr.push({
                id: spec.id,
                paramValue: ''
              })
            }
          })
          this.specKV.push(KVarr)
          group['data'] = arr
        })
        this.specparam = groupArr
      })
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
  mounted() {
    this.getCategorys()
  }
}
</script>
